package com.example.jpatest.controller.restful;

import com.example.jpatest.entity.Competition;
import com.example.jpatest.exception.competitionException.CompetitionExistException;
import com.example.jpatest.exception.competitionException.CompetitionNotExistException;
import com.example.jpatest.service.impl.CompetitionServiceImpl;
import com.example.jpatest.unit.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author czx
 */
@RestController
public class CompetitionController {
    @Autowired
    CompetitionServiceImpl competitionService;

    /**
     * 添加赛事
     */
    @PostMapping("/competition")
    public Result addCompetition(@RequestBody Competition competition){
        if (competitionService.getCompetitionByName(competition.getName())!=null) {
            throw new CompetitionExistException();
        }
        competitionService.saveCompetition(competition);
        return Result.succMsg();
    }

    /**
     * 获得所有赛事
     */
    @GetMapping("/competitions")
    public Result competitions(){
        return Result.succ(competitionService.getCompetitions());
    }

    /**
     * 根据赛事名查找赛事
     */
    @GetMapping("/competition/{name}")
    public Result getCompetitionByName(@PathVariable String name){
        Competition competition = competitionService.getCompetitionByName(name);
        if(competition==null){
            throw new CompetitionNotExistException();
        }
        return Result.succ(competition);
    }

    /**
     * 更新赛事
     */
    @PutMapping("/competition")
    public Result updateCompetition(@RequestBody Competition competition){
        Competition competitionByName = competitionService.getCompetitionByName(competition.getName());
        if (competitionByName ==null) {
            throw new CompetitionNotExistException();
        }
        competition.setId(competitionByName.getId());
        competitionService.saveCompetition(competition);
        return Result.succMsg();
    }

    /**
     * 删除赛事
     */
    @DeleteMapping("/competition/{name}")
    public Result deleteCompetition(@PathVariable String name){
        Competition competition = competitionService.getCompetitionByName(name);
        if (competition==null) {
            throw new CompetitionNotExistException();
        }
        competitionService.deleteCompetition(competition);
        return Result.succMsg();
    }

    /**
     * 获得赛事所有报名队伍
     */
    @GetMapping("/competition/{name}/teams")
    public Result getTeams(@PathVariable String name){
        Competition competition = competitionService.getCompetitionByName(name);
        if (competition==null) {
            throw new CompetitionNotExistException();
        }
        return Result.succ(competitionService.getTeams(competition));
    }
}
